package ucl.cs.stockBroker.server;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.rmi.RemoteException;

import ucl.cs.stockBroker.common.Stock;
import ucl.cs.stockBroker.common.StockBroker;

public class Stocks implements Runnable {

	private StockBroker stockBroker;
	private Stock[] tempStocks = new Stock[10];

	public Stocks(StockBroker stockBroker) {
		this.stockBroker = stockBroker;
	}

	public void run() {
		while (true) {

			getStocksFromURL();

			try {
				stockBroker.addStocks(tempStocks);

				Thread.sleep(300 * 1000); // 5 minutes
			} catch (RemoteException e) {
				System.out.println(e);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	@SuppressWarnings("deprecation")
	private void getStocksFromURL() {

		URL u;
		InputStream is = null;
		DataInputStream dis = null;
		String s;

		try {

			u = new URL(
					"http://quote.yahoo.com/d/quotes.csv?s=BARC.L+BAY.L+CW.L+LLOY.L"
							+ "+RBS.L+RR.L+SBRY.L+TSCO.L+VOD.L+ISAT.L&f=snl1");

			is = u.openStream();
			dis = new DataInputStream(new BufferedInputStream(is));

			int i = 0;
			while ((s = dis.readLine()) != null) {
				tempStocks[i] = createStock(s);
				i++;
			}

		} catch (IOException ioe) {
		}

	}

	private Stock createStock(String urlString) throws RemoteException {
		Stock stock;
		String symbol;
		String name;
		float price;

		String[] tempArray = urlString.split(",");
		symbol = tempArray[0].replaceAll("\"", "").trim();
		name = tempArray[1].replaceAll("\"", "").trim();
		price = Float.valueOf(tempArray[2]);

		stock = new Stock(symbol, name, price);

		return stock;
	}

}
